package com.cloud.io;

import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;

/**
 * 在线程A中向PipedOutputStream中写入数据，
 * 这些数据会自动的发送到与PipedOutputStream对应的PipedInputStream中，
 * 进而存储在PipedInputStream的缓冲中；
 * 此时，线程B通过读取PipedInputStream中的数据
 *
 */
public class PipeStreamTest {
    public static void main(String[] args) throws IOException {
        final PipedOutputStream output = new PipedOutputStream();
        final PipedInputStream input = new PipedInputStream(output);

        //创建2个线程
        Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    output.write("Hello Pipe".getBytes());
                    output.close();
                } catch(IOException e) {
                    e.printStackTrace();
                }
            }
        });
        Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    int data = input.read();
                    while(data != -1) {
                        System.out.print((char)data);
                        data = input.read();
                    }
                    input.close();
                    System.out.println();
                } catch(IOException e) {
                    e.printStackTrace();
                }
            }
        });
        thread1.start();
        thread2.start();

    }
}
